package th.retrofit.lib;

public class Solution110 {

    public boolean isBalanced(TreeNode root) {
        return getBalancedDepth(root) != -1;
    }

    public int getBalancedDepth(TreeNode root) {
        if (root == null) return 0;
        int leftDepth, rightDepth;
        if ((leftDepth = getBalancedDepth(root.left)) == -1 || (rightDepth = getBalancedDepth(root.right)) == -1 || Math.abs(leftDepth - rightDepth) > 1) {
            return -1;
        }
        return Math.max(leftDepth, rightDepth) + 1;
    }

    public static void main(String[] args) {
        TreeNode root = TreeNode.array2Tree(1,2,2,3,3,null,null,4,4);
        System.out.println(new Solution110().isBalanced(root));
    }

}
